package com.flyoil.petromp.view;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.RelativeLayout;
import android.widget.TextView;


import com.cnpc.fyimageloader.glide.GlideHelper;
import com.cnpc.fyutils.BaseUtils;
import com.cnpc.fyutils.Constants;
import com.cnpc.fyutils.SystemUtils;
import com.flyoil.petromp.R;

import java.lang.ref.WeakReference;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;


/**
 * 顶部广告的ViewPager
 *
 * @author Stone
 */
public class RollViewPagerFitXY extends ViewPager {
    private final static String TAG = "RollViewPagerFitXY";

    public RollViewPagerFitXY(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.ct = context;
    }

    private Activity mActivity;
    private Context ct;
    private List<View> dotList;
    private int dotFocus;
    private int dotNormal;
    private TextView tvDescription;
    private float mLastMotionX;
    private float mLastMotionY;

//	private TaskPager taskPager;

    private boolean isCanScroll = true;

    private Application application;

    private MyHandler myHandler;

    public interface OnPagerClickCallBack {
        void pagerClickCallBack(int position);
    }

    public interface MyOnTouchCllickCallBack {
        void OnTouchCllick(int position);
    }

    public MyOnTouchCllickCallBack onTouchCllickCallBack;

    public RollViewPagerFitXY(Application application, Context ct, List<View> dotList, int dotFocus, int dotNormal,
                              MyOnTouchCllickCallBack myOnTouchCllickCallBack) {
        super(ct);
        this.application = application;
        this.ct = ct;
        this.dotList = dotList;
        this.dotFocus = dotFocus;
        this.dotNormal = dotNormal;
        this.mActivity = (Activity) ct;
//		 taskPager = new TaskPager();
        this.onTouchCllickCallBack = myOnTouchCllickCallBack;
        myOnTouchListener = new MyOnTouchListener();
        myHandler = new MyHandler(RollViewPagerFitXY.this);
    }

    @Override
    public void scrollTo(int x, int y) {
        if (dotList != null && dotList.size() <= 1) {
            return;
        }
        super.scrollTo(x, y);
    }

    public class MyOnTouchListener implements OnTouchListener {

        private long satartCurrentTimeMillis;

        @Override
        public boolean onTouch(View arg0, MotionEvent arg1) {
            float currentX = arg1.getX();
            float currentY = arg1.getY();
            switch (arg1.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    satartCurrentTimeMillis = System.currentTimeMillis();
//				myHandler.removeCallbacksAndMessages(null);
                    isCanScroll = false;
                    break;

                case MotionEvent.ACTION_UP:
                    long duration = System.currentTimeMillis() - satartCurrentTimeMillis;
                    float upX = arg1.getX();
                    if (duration < 500 && upX == currentX) {
                        if (!BaseUtils.isFastDoubleClick()) {
                            if (onTouchCllickCallBack != null)
                                onTouchCllickCallBack.OnTouchCllick(currentItem);
                        }

                    }
                    isCanScroll = true;
//				 startRoll();
                case MotionEvent.ACTION_CANCEL:
//				 startRoll();
                    isCanScroll = true;
                    break;
                case MotionEvent.ACTION_MOVE:
                    isCanScroll = false;
//				 myHandler.removeCallbacksAndMessages(null);
                    break;
            }
            return true;
        }

    }
//	public boolean onInterceptTouchEvent(MotionEvent ev) {
//		// TODO Auto-generated method stub
//		//当拦截触摸事件到达此位置的时候，返回true，
//		//说明将onTouch拦截在此控件，进而执行此控件的onTouchEvent
//		/*--------------------------------------------------------*/
//		switch (ev.getAction()) {
//			case MotionEvent.ACTION_DOWN:
//				Log.i(TAG, "onInterceptTouchEvent--->ACTION_DOWN");
//				break;
//			case MotionEvent.ACTION_MOVE:
//				Log.i(TAG, "onInterceptTouchEvent--->ACTION_MOVE");
//				break;
//		}
//		boolean test = super.onInterceptTouchEvent(ev);
////		Log.i(TAG, "super.onInterceptTouchEvent--->"+test);
//		/*--------------------------------------------------------*/
//
//		return super.onInterceptTouchEvent(ev);
//	}

//	@Override
//	public boolean onTouchEvent(MotionEvent ev) {
//		switch (ev.getAction()) {
//			case MotionEvent.ACTION_DOWN:
//				Log.i(TAG, "onTouchEvent--->ACTION_DOWN");
//				break;
//			case MotionEvent.ACTION_MOVE:
//				Log.i(TAG, "onTouchEvent--->ACTION_MOVE");
//				break;
//		}
//		boolean test = super.onTouchEvent(ev);
////		Log.i(TAG, "super.onTouchEvent--->"+test);
//		return super.onTouchEvent(ev);
//	}

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        final float x = ev.getX();
        final float y = ev.getY();
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                if (null != this.getParent()) {
                    this.getParent().requestDisallowInterceptTouchEvent(true);
                }
                mLastMotionX = x;
                mLastMotionY = y;
                break;
            case MotionEvent.ACTION_MOVE:
                if (Math.abs(x - mLastMotionX) < Math.abs(y - mLastMotionY)) {
                    if (null != this.getParent()) {
                        this.getParent().requestDisallowInterceptTouchEvent(false);
                    }
                } else {
                    if (null != this.getParent()) {
                        this.getParent().requestDisallowInterceptTouchEvent(true);
                    }
                    Log.d(TAG, "in viewpager");
                }
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                if (null != this.getParent()) {
                    this.getParent().requestDisallowInterceptTouchEvent(false);
                }
                break;
        }


        return super.dispatchTouchEvent(ev);
    }


    // 需要显示的文本内容
    private List<String> titleList;

    public void setTitle(TextView tvDescription, List<String> titleList) {
        this.tvDescription = tvDescription;
        this.titleList = titleList;
        if (tvDescription != null && titleList != null && titleList.size() > 0) {
            tvDescription.setText(titleList.get(0));
        }
    }

    private List<String> imageUrlList;
    private List<Integer> drawableInt;
    private ViewPagerAdatper adapter;

    //有效避免OOM异常
    public static class MyHandler extends Handler {
        private WeakReference<RollViewPagerFitXY> mActivityReference;

        public MyHandler(RollViewPagerFitXY activity) {
            mActivityReference = new WeakReference<RollViewPagerFitXY>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            RollViewPagerFitXY activity = mActivityReference.get();
            if (activity != null) {
                if (msg.what == 1) {
                    activity.setCurrentItem(activity.getCurrentItem() + 1);
                }
            }
        }
    }

    Timer myTimer = new Timer();
    TimerTask myTimerTask = new TimerTask() {

        @Override
        public void run() {
            // 需要做的事:发送消息
            Message message = Message.obtain();
            message.what = 1;
            if (imageUrlList.size() > 1 && isCanScroll) {
                currentItem = (currentItem + 1) % imageUrlList.size();
                if (myHandler == null) {
                    myHandler = new MyHandler(RollViewPagerFitXY.this);
                }
                myHandler.sendMessage(message);
            }
        }
    };

    //

    public void setImageUrl(List<String> imageUrlList) {
        this.imageUrlList = imageUrlList;
    }

    public void setDrawableInt(List<Integer> drawableInt) {
        this.drawableInt = drawableInt;
    }

    public boolean hasSetAdapter = false;

    public void startRoll() {
        if (!hasSetAdapter) {
            hasSetAdapter = true;
            this.setOnPageChangeListener(new MyOnPageChangeListener());


            adapter = new ViewPagerAdatper();
            this.setAdapter(adapter);
        }
//		 handler.postDelayed(taskPager, 4000);
        myTimer.schedule(myTimerTask, 1000, 5000);

    }

    public static int currentItem = 0;
    public static int startItem = 0;
    private MyOnTouchListener myOnTouchListener;
    private SharedPreferences sp;

    public class MyOnPageChangeListener implements OnPageChangeListener {
        int oldPositionItem = 0;

        @Override
        public void onPageScrollStateChanged(int arg0) {

        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {

        }

        @Override
        public void onPageSelected(int arg0) {
            currentItem = arg0 % dotList.size();
            if (tvDescription != null) {
                tvDescription.setText(titleList.get(arg0 % titleList.size()));
            }
            if (dotList != null && dotList.size() > 1) {
                dotList.get(arg0 % dotList.size()).setBackgroundResource(dotNormal);
                dotList.get(oldPositionItem % dotList.size()).setBackgroundResource(dotFocus);
            }
            oldPositionItem = arg0;
        }

    }

    public class ViewPagerAdatper extends PagerAdapter {

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            if (Constants.sScreenWidth == 0 || Constants.sScreenHeight == 0) {
                SystemUtils.getScreen(mActivity);
            }
            ImageView iv = new ImageView(ct);
//			iv.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT,
//					Constants.sScreenWidth * 248 / 640));
            iv.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, Constants.sScreenWidth * 268 / 750));

            // HhyjImageLoader.getInstance().displayImage(imageUrlList.get(position
            // % dotList.size()),
            // iv);

            iv.setScaleType(ScaleType.FIT_XY);
            String imagePath = imageUrlList.get(position % dotList.size());
            int[] banner = new int[]{R.mipmap.banner1, R.mipmap.banner2, R.mipmap.banner3};
            if (!TextUtils.isEmpty(imagePath)) {
                //todo 正在加载中时，还没处理
                if (position % dotList.size() < 3) {
                    GlideHelper.showImage(ct, imagePath, iv, banner[position % dotList.size()]);
                } else {
                    GlideHelper.showImage(ct, imagePath, iv, R.mipmap.banner_loding);
                }

            }

            iv.setOnTouchListener(myOnTouchListener);
            container.addView(iv);
            return iv;
        }

        @Override
        public int getCount() {
            return Integer.MAX_VALUE;
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

    }

    public void removeMessage() {
        if (myHandler != null) {
            myHandler.removeCallbacksAndMessages(null);
        }
    }

    @Override
    protected void onDetachedFromWindow() {
//		 handler.removeCallbacksAndMessages(null);
        super.onDetachedFromWindow();
    }
}
